package com.fourfinance.model.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fourfinance.model.dao.LoanDAO;
import com.fourfinance.model.domain.Loan;

@Repository
public class LoanDAOImpl implements LoanDAO {
	
	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public Long add(Loan loan) {
		return (Long) sessionFactory.getCurrentSession().save(loan);
	}

	@Override
	public Loan get(Long id) {
		return (Loan) sessionFactory.getCurrentSession().get(Loan.class, id);
	}

	@Override
	public List<Loan> list() {
		return sessionFactory.getCurrentSession().createQuery("from Loan").list();
	}

	@Override
	public void remove(Long id) {
		Loan Loan = (Loan) sessionFactory.getCurrentSession().load(Loan.class, id);
		if (null != Loan) {
			sessionFactory.getCurrentSession().delete(Loan);
		}
	}

	@Override
	public void removeAll() {
		sessionFactory.getCurrentSession().createQuery("delete from Loan");
	}

	@Override
	public Loan getByReferenceId(String referenceId) {
		Query query = sessionFactory.getCurrentSession().createQuery("from Loan where referenceId = :referenceId");
		query.setParameter("referenceId", referenceId);
		return (Loan) query.uniqueResult();
	}
	
	@Override
	public void update(Loan loan) {
		sessionFactory.getCurrentSession().update(loan);
	}

}
